<template>
  <div class="product-add">
    <el-card>
      <template #header>
        <span class="card-title">基础信息</span>
      </template>
      
      <el-form :model="formData" :rules="rules" ref="formRef" label-width="120px">
        <el-row :gutter="20">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="货品名称" prop="productName" required>
              <el-input v-model="formData.productName" placeholder="请输入" />
            </el-form-item>
            
                         <el-form-item label="货品编号" prop="productNo" required>
               <el-input v-model="formData.productNo" placeholder="不输入则自动获取编号" />
               <el-button type="primary" size="small" style="margin-left: 10px" @click="generateProductNo">自动生成</el-button>
             </el-form-item>
            
                         <el-form-item label="规格型号" prop="productModel">
               <el-input v-model="formData.productModel" placeholder="请输入" />
             </el-form-item>
             
             <el-form-item label="单位" prop="unitName">
               <el-select v-model="formData.unitName" placeholder="请选择" style="width: 100%">
                 <el-option label="个" value="个" />
                 <el-option label="元" value="元" />
                 <el-option label="件" value="件" />
                 <el-option label="包" value="包" />
                 <el-option label="KG" value="KG" />
                 <el-option label="瓶" value="瓶" />
               </el-select>
             </el-form-item>
             
             <el-form-item label="条形码" prop="barcode">
               <el-input v-model="formData.barcode" placeholder="请输入" />
             </el-form-item>
            
            <el-form-item label="状态" prop="status" required>
              <el-radio-group v-model="formData.status">
                <el-radio :label="true">启用</el-radio>
                <el-radio :label="false">停用</el-radio>
              </el-radio-group>
            </el-form-item>
            
                         <el-form-item label="保质期(天)" prop="shelflifedays">
               <el-input v-model="formData.shelflifedays" placeholder="请输入" />
             </el-form-item>
             
             <el-form-item label="预警天数(天)" prop="alertdays">
               <el-input v-model="formData.alertdays" placeholder="请输入" />
             </el-form-item>
            
            <el-form-item label="备注" prop="remarks">
              <el-input v-model="formData.remarks" type="textarea" :rows="3" placeholder="请输入" />
            </el-form-item>
          </el-col>
          
          <!-- 右列 -->
          <el-col :span="12">
                         <el-form-item label="货品类型" prop="productTypeId">
               <el-select v-model="formData.productTypeId" placeholder="请选择" style="width: 100%">
                 <el-option label="电子产品" value="电子产品" />
                 <el-option label="服装" value="服装" />
                 <el-option label="食品" value="食品" />
                 <el-option label="日用品" value="日用品" />
               </el-select>
             </el-form-item>
             
             <el-form-item label="仓库" prop="inventory">
               <el-select v-model="formData.inventory" placeholder="请选择" style="width: 100%">
                 <el-option label="仓库一" value="仓库一" />
                 <el-option label="仓库二" value="仓库二" />
                 <el-option label="仓库三" value="仓库三" />
               </el-select>
             </el-form-item>
             
             <el-form-item label="库位" prop="location">
                <el-select v-model="formData.location" placeholder="请选择" style="width: 100%">
                 <el-option label="库位一" value="库位一" />
                 <el-option label="库位二" value="库位二" />
                 <el-option label="库位三" value="库位三" />
               </el-select>
             </el-form-item>
             <el-form-item label="批次" prop="batch">
                <el-input v-model="formData.batch" placeholder="请输入" />
              </el-form-item>
             
             <el-form-item label="生产日期" prop="productiondate">
               <el-date-picker
                 v-model="formData.productiondate"
                 type="date"
                 placeholder="请选择生产日期"
                 style="width: 100%"
                 format="YYYY-MM-DD"
                 value-format="YYYY-MM-DD"
               />
             </el-form-item>
             
             <el-form-item label="到期日期" prop="expirationdate">
               <el-date-picker
                 v-model="formData.expirationdate"
                 type="date"
                 placeholder="请选择到期日期"
                 style="width: 100%"
                 format="YYYY-MM-DD"
                 value-format="YYYY-MM-DD"
               />
             </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { TZRead,TZWrite } from '@/http/interceptors'

const formRef = ref()

// 表单数据
const formData = reactive({
   "productNo": "",//货品编号
  "productName": "",//货品名称
  "productTypeId": "",//货品类型
  "productModel": "",//规格型号
  "status": true,//货品状态
  "unitName": "",//单位
  "barcode": "",//条形码
  "inventory": "",//仓库
  "location": "",//库位
  "current_Inventory":0,//当前库存
  "totalMoeny": 0,//库存金额
  "remarks": "",//备注
  "batch": "",//批次
  "productiondate": "",//生产日期
  "expirationdate": "",//到期日期
  "shelflifedays": "",//保质期
  "remainingdays": 0,//剩余天数
  "alertdays": "",//预警天数
  "createer": ""//创建人(可选,后端添加)
})

// 表单验证规则
const rules = {
  productName: [
    { required: true, message: '请输入货品名称', trigger: 'blur' }
  ],
  productNo: [
    { required: true, message: '请输入货品编号', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  unitName: [
    { required: true, message: '请选择单位', trigger: 'change' }
  ],
  inventory: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ]
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    console.log('表单数据:', formData)
    TZWrite.post("/api/ProductAddProduct",formData).then(res=>{
      if(res.data.code==200)
      {
        ElMessage.success(res.data.message)
        // 保存成功后清空表单数据
        clearFormData()
      }
      else
      {
          ElMessage.error(res.data.message)
      }
    })
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

// 清空表单数据
const clearFormData = () => {
  // 重置所有字段为初始值
  Object.assign(formData, {
    productNo: "",
    productName: "",
    productTypeId: "",
    productModel: "",
    status: true,
    unitName: "",
    barcode: "",
    inventory: "",
    location: "",
    current_Inventory: "",
    totalMoeny: "",
    remarks: "",
    batch: "",
    productiondate: "",
    expirationdate: "",
    shelflifedays: "",
    remainingdays: "",
    alertdays: "",
    createer: ""
  })
  
  // 重新生成货品编号和批次
  generateProductNo()
  generateBatch()
}

// 重置表单
const handleReset = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
  // 手动重置数值字段为空字符串
  formData.current_Inventory = ""
  formData.totalMoeny = ""
  formData.shelflifedays = ""
  formData.remainingdays = ""
  formData.alertdays = ""
  ElMessage.info('表单已重置')
}

// 自动生成货品编号
const generateProductNo = () => {
  // 生成格式：P + 年月日 + 4位随机数
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  
  const productNo = `P${year}${month}${day}${random}`
  formData.productNo = productNo
  
  ElMessage.success('货品编号已自动生成')
}

// 自动生成批次
const generateBatch = () => {
  // 生成格式：年月日
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  
  const batch = `${year}${month}${day}`
  formData.batch = batch
  
  ElMessage.success('批次已自动生成')
}

// 取消
const handleCancel = () => {
  ElMessage.info('已取消')
  // 这里可以返回上一页或关闭弹窗
}

// 页面加载时自动生成货品编号和批次
onMounted(() => {
  generateProductNo()
  generateBatch()
})
</script>

<style scoped>
.product-add {
  padding: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-button {
  margin-right: 10px;
}
</style> 